import { FilmMultimediaRelation } from "../entities/filmMultimediaRelation";
import dayjs from "dayjs";
import { PlatformUserAccountExpiredError } from "../libs/errors";

export class PlatformDouyinPublishJob {
  constructor(opt) {
    this.sequelize = opt.sequelize;
    this.platformFactory = opt.platformFactory;
    this.filmReleaseService = opt.filmReleaseService;
    this.platformUserAccountService = opt.platformUserAccountService;
  }

  async execute(data){
    try {
      let platformUserAccount = await this.platformUserAccountService.getFirstAccountUser(data.platform_account_user_id);

      if ((!platformUserAccount) || (platformUserAccount.result.status === 0)) {
        throw new PlatformUserAccountExpiredError('所选授权账号异常');
      } else {
        platformUserAccount = platformUserAccount.result
      }

      // 更新状态为发布中
      await this.filmReleaseService.updateFilmMultimediaRelationStatus(data.id, {
        release_status: FilmMultimediaRelation.RELEASE_STATUS_PROGRESS
      });
      
      const platform = this.platformFactory.create(platformUserAccount);
      
      // 获取授权用户信息 检查需不需要重新登录
      await platform.getUserAccount()

      // 发布视频
      const syncRes = await platform.syncVideoRelease(data);

      // 更新状态为发布成功
      await this.filmReleaseService.updateFilmMultimediaRelationStatus(data.id, {
        release_status: FilmMultimediaRelation.RELEASE_STATUS_SUCCESS,
        release_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        api_result: syncRes,
      });
    } catch (error) {
      if (error instanceof PlatformUserAccountExpiredError) {
        // todo 修改账号状态为过期状态
        await this.platformUserAccountService.updateAccountUserStatus(data.platform_account_user_id, 0);
      }

      await this.filmReleaseService.updateFilmMultimediaRelationStatus(data.id, {
        release_status: FilmMultimediaRelation.RELEASE_STATUS_FAIL,
        release_reason: error.message,
        api_failed: error.message,
      });

      throw error;
    }
  }
}